package com.example.uploadpic.demo.service;

import org.apache.juli.logging.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;


@Service
public class FileService {
    @Value("${server.port}")
    private String port;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${pic.dir}")
    private String picDir;

    public String saveFile(MultipartFile multipartFile){
        String filename=multipartFile.getOriginalFilename();
        File file=new File(picDir+filename);
        try {
            multipartFile.transferTo(file);
        }catch (IOException e){
            System.out.println("save file error,{}"+e.getMessage());
            return "";
        }
        return getFileUrl(filename);
    }

    private String getFileUrl(String filename) {
        try{
            InetAddress address=InetAddress.getLocalHost();
            String fileUrl="http://"+address.getHostAddress()+":"+port+contextPath+"/file/"+filename;
            return fileUrl;
        }catch (UnknownHostException e){
            System.out.println("get host error,{}"+e.getMessage());
            return "";
        }
    }
}
